package com.tfy.liquor.service.impl;

import com.tfy.liquor.bean.*;
import com.tfy.liquor.dao.UserInfoDao;
import com.tfy.liquor.dao.UserPurseDao;
import com.tfy.liquor.service.UserPriseRecordsService;
import com.tfy.liquor.service.UserPurseService;
import com.tfy.liquor.util.CodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

// 用户钱包信息
@Service
public class UserPurseServiceImpl implements UserPurseService {
    @Autowired
    private UserInfoDao userPurse;
    @Autowired
    private UserPurseDao userPurseDao;
    @Autowired
    private UserPriseRecordsService userPriseRecordsService;

    // 创建钱包
    @Override
    public Boolean createUserPurse(UserPurse userPurse) {
        // 加密用户设置的操作密码
        userPurse.setOpCode(CodeUtils.md5Hex(userPurse.getOpCode(), userPurse.getUserId().toString()));
        return userPurseDao.createUserPurse(userPurse) > 0;
    }

    // 根据用户编号获取钱包信息
    @Override
    public UserPurse getUserPurseByUserId(Long userId) {
        return userPurseDao.getUserPurseByUserId(userId);
    }

    // 修改钱包操作码
    @Override
    public Result editUserPurseOpCode(UserPurse userPurse, String oldOpCode) {
        // 验证用户原始密码
        String oldOpCode1 = userPurseDao.getUserPurseOpCode(userPurse.getUserId()).getOpCode();
        if (oldOpCode1.equals(CodeUtils.md5Hex(oldOpCode, userPurse.getUserId().toString()))) {
            // 加密用户设置的操作密码
            userPurse.setOpCode(CodeUtils.md5Hex(userPurse.getOpCode(), userPurse.getUserId().toString()));
            if (userPurseDao.editUserPurseOpCode(userPurse) > 0) {
                return new Result().ok("操作码修改成功！");
            } else {
                return new Result().error("操作码修改失败！");
            }
        }
        return new Result().error("原始密码错误！");
    }

    // 订单分润记录
    @Override
    public Boolean orderEarnings(ProductOrder productOrder) {
        // 获取上级推荐人信息
        UserInfo userInfo = userPurse.getSuperiorUserInfo(productOrder.getUserId());
        // 如果没有上级推荐人，则不分润
        if (null == userInfo || null == userInfo.getUserId()) {
            return false;
        }
        // 获取上级钱包信息
        UserPurse userPurse = userPurseDao.getUserPurseByUserId(userInfo.getUserId());
        // 计算应该分润金额
        BigDecimal amount = productOrder.getActualPayment().multiply(new BigDecimal("0.8"));
        // 计算分润后总金额
        BigDecimal afterAmount = userPurse.getFreezeBalance().add(amount);
        // 添加记录
        UserPriseRecords userPriseRecords = new UserPriseRecords(userPurse.getUserId(), amount, afterAmount, productOrder.getOrderId());
        userPriseRecords.setRemark("订单分润");
        // 先添加流水记录
        if (userPriseRecordsService.addUserPriseRecords(userPriseRecords)) {
            userPurse.setFreezeBalance(afterAmount);
            // 再修改钱包数据
            return userPurseDao.editUserPurseFreezeBalance(userPurse) > 1;
        }
        return false;
    }
}
